package com.ticktick.jnibuffer;

import java.nio.ByteBuffer;

import android.util.Log;

public class Native {
	private static final String TAG = "JniBuffer";
	public static final int TEST_BUFFER_SIZE = 128;

	private byte[] mTestBuffer1;
	private byte[] mTestBuffer2;
	private ByteBuffer mDirectBuffer;
	
	private native void nativeSetBuffer1(byte[] buffer,int len);
	private native void nativeSetBuffer2(byte[] buffer,int len);
	private native void nativeSetDirectBuffer(Object buffer, int len);
	private native byte[] nativeGetByteArray();

	public native void RegisterCallback();
	
	public Native() {
		mTestBuffer1 = new byte[TEST_BUFFER_SIZE];
		mTestBuffer2 = new byte[TEST_BUFFER_SIZE];
		mDirectBuffer = ByteBuffer.allocateDirect(TEST_BUFFER_SIZE);
//		RegisterCallback();
	}
	
	public void test() {
        
		nativeSetBuffer1(mTestBuffer1,TEST_BUFFER_SIZE);
        printBuffer("nativeInitNormalBuffer",mTestBuffer1);
                
        nativeSetBuffer2(mTestBuffer2,TEST_BUFFER_SIZE);
        printBuffer("nativeInitNormalBuffer2",mTestBuffer2);

		//Direct buffer 方式传递
        nativeSetDirectBuffer(mDirectBuffer,TEST_BUFFER_SIZE);
		Log.d("Native", "test: mDirectBuffer.array() = " + mDirectBuffer.array().length);
		printBuffer("nativeInitDirectBuffer",mDirectBuffer.array());
        
        byte[] buffer = nativeGetByteArray();        
        printBuffer("nativeGetByteArray",buffer);
	}

	public void MyTest() {
		Log.d(TAG, "MyTest: Start time:" + System.currentTimeMillis());
		RegisterCallback();
	}
	
	private void printBuffer( String tag, byte[] buffer ) {
		StringBuffer sBuffer = new StringBuffer();
		sBuffer.append(" ");
		for( int i=0; i<buffer.length; i++ ) {
			sBuffer.append(buffer[i]);
			sBuffer.append(" ");	
		}
		Log.d("Native", tag + sBuffer.toString());
	}
	
    static {
        System.loadLibrary("native");
    }

	private static int callback_times = 0;
	void dataCallbackMethod1(byte[] buffer) {
		for(int i=0; i<buffer.length; i++) {
			if(i%5000 == 0)
				Log.d(TAG, "dataCallbackMethod1: " + buffer[i]);
		}
		callback_times++;
		Log.d(TAG, "dataCallbackMethod1: callback_times = " + callback_times
				+ " Currunt time:" + System.currentTimeMillis());
	}
}
